﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http;
using WooCoo.Reflection;

namespace WooCoo.DataPortal.Server.Hosts
{
    public class WebApiPortal : ApiController
    {
        [HttpPost]
        public DataPortalResult Create(string contactName, string criteria)
        {
            throw new NotImplementedException();           
        }

        public DataPortalResult Fetch(string contactName, string criteria)
        {
            throw new NotImplementedException();
        }
        [HttpPost]
        public DataPortalResult Update([FromBody]ActionInfo req)
        {
            throw new NotImplementedException();
        }
        [HttpGet,HttpPost]
        public DataPortalResult Delete(string contactName, object criteria)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 执行接口方法
        /// </summary>
        /// <param name="reqMessage"></param>
        /// <returns></returns>
        [HttpPost]
        public DataPortalResult Execute([FromBody]ActionInfo req)
        {
            DataPortalFacade dpf = new DataPortalFacade();
            ActionInfo actionInfo = req;
            object export;
            WooCoo.IoC.Container.Current.TryGetExports(actionInfo.ContractName, out export);
            var types = MethodCaller.GetCachedMethodParamesterTypes(export.GetType(), actionInfo.MethodName, actionInfo.Parameters.Count());
            for (int i = 0; i < types.Length; i++)
            {
                if (actionInfo.Parameters[i] is Newtonsoft.Json.Linq.JContainer)
                    actionInfo.Parameters[i] = Newtonsoft.Json.JsonConvert.DeserializeObject(actionInfo.Parameters[i].ToString(), types[i]);
                else
                    actionInfo.Parameters[i] = TypeHelper.CoerceValue(types[i], actionInfo.Parameters[i]);
            }
            return dpf.Execute(actionInfo, ParseRequest());
        }

        private DataPortalContext ParseRequest()
        {
            DataPortalContext result = new DataPortalContext();
            result.SessionID = Request.Headers.GetValues("WooCooSessionID").FirstOrDefault();
            result.TransactionType = TypeHelper.CoerceValue<TransactionType>(Request.Headers.GetValues("WooCooTransType").FirstOrDefault());
            return result;
        }
    }
}
